package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    IScheduleClient scheduleClient;

    @Autowired
    WmNewsAutoScanService wmNewsAutoScanService;

    @Override
    public void addNewsToTask(WmNews wmNews) {
        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime()); //时间
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType()); //文章定时审核
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //google 序列号对象
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        scheduleClient.addTask(task);
    }

    //可以每隔一秒钟去拉任务
    @Override
    @Scheduled(cron = "0/1 * * * * ? ") //消费者
    public void listener() {
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(responseResult.getCode()==200&&responseResult.getData()!=null){
            String json_str = JSON.toJSONString(responseResult.getData()); //json
            Task task = JSON.parseObject(json_str, Task.class);
            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            System.out.println(wmNews.getId()+"-----------");
            wmNewsAutoScanService.autoScanWmNews(wmNews);
        }
    }
}
